package net.kingborn.core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * 安全相关工具
 * 
 * @author David Chen
 *
 */
@SuppressWarnings("restriction")
public class SecKit {

	/**
	 * Base64编码
	 * 
	 * @param raw
	 * @return
	 */
	public static String base64Encode(String raw) {
		if (raw == null) {
			throw new IllegalArgumentException("input should not be null");
		}
		
		return new BASE64Encoder().encode(raw.getBytes());
	}
	
	/**
	 * Base64解码
	 * 
	 * @param encrypt
	 * @return
	 */
	public static String base64Decode(String encrypt) {
		if (encrypt == null) {
			throw new IllegalArgumentException("input should not be null");
		}
		
		try {
			return new String(new BASE64Decoder().decodeBuffer(encrypt));
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 创建密码盐
	 * 
	 * @return
	 */
	public static String createPasswordSalt() {
		return MathKit.baseConvert(HashKit.sha1(Util.randomUUID()), 16, 36).toLowerCase();
	}
	
	/**
	 * 对密码加密
	 * 
	 * @param password
	 * @param salt
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String encodePassword(String password, String salt) {
		String salted = password + "{" + salt + "}";
		String digest = HashKit.sha1(salted);
		
		// 对密码进行5000次sha1加密
		for (int index = 1; index < 5000; index ++) {
			digest = HashKit.sha1(digest + salted);
		}
		
		return base64Encode(digest);
	}
	

	/**
	 * 产生随机字符串
	 * 
	 * @param i
	 * @param b
	 * @return
	 */
	public static String randomStr(int length, boolean hasNumber) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		if (!hasNumber) {
			base = "abcdefghijklmnopqrstuvwxyz";
		}

		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}

		return sb.toString();
	}
	
	/**
	 * 产生随机数值字符
	 * 
	 * @param length
	 * @return
	 */
	public static String randomNumericStr(int length) {
		String base = "0123456789";

		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}

		return sb.toString();
	}
}
